<?php

namespace common\models\rfid;

use Yii;

/**
 * This is the model class for table "{{%rfid}}".
 *
 * @property int $id
 * @property int $bill_id 票据ID
 * @property string $sn 电子标签序列号
 * @property int $actived_at 生效时间
 * @property int $expired_at 过期时间
 * @property int $company_id 公司单位ID
 * @property int $master 留存标识
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class Rfid extends \common\db\ActiveRecord implements \common\base\OrderNoInterface {

    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;

    use \common\traits\GenerateUniqueNumber;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%rfid}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['bill_id', 'actived_at', 'expired_at', 'company_id', 'master', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['sn'], 'required'],
            [['sn'], 'string', 'max' => 32],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'bill_id' => '票据ID',
            'sn' => '电子标签序列号',
            'actived_at' => '生效时间',
            'expired_at' => '过期时间',
            'company_id' => '公司单位ID',
            'master' => '留存标识',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    public function getBill() {
        return $this->hasOne(\common\models\bill\Bill::className(), ['id' => 'bill_id']);
    }

    public function generateNo() {
        $checkBit = $this->generateCheckBitChar($this->bill_id, true);
        $from = base_convert($checkBit, 10, 16); //转为32进制
        $rules = [
            'from' => str_pad($from, 4, 0, STR_PAD_LEFT),
        ];
        return $this->sn = $this->generateUniqueNumber('sn', $rules);
    }

    /**
     * 获取账号密码重置token
     * @param string $sn password reset token
     * @return static|null
     */
    public static function findBySn($sn, $type, $status = self::STATUS_ACTIVE) {
        return static::findActive('t', $status)
        ->joinWith('bill b')
        ->andWhere([
            't.sn' => $sn,
            'b.type_id' => $type,
        ])->one();
    }

    public function setActived() {
        $this->actived_at = time();
        $this->expired_at = $this->actived_at + 2 * 365 * 86400;
        $this->status = self::STATUS_ACTIVE;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'id' => 'sn',
            'data' => function() {
                $code = strtoupper(dechex($this->id));
                return str_pad($code, 8, 0, STR_PAD_LEFT);
            },
        ];
    }

}
